﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace KZ400B.Link
{
    public class TCPLink:LinkBase
    {
        private Socket m_Client;

        private object m_readLokcer = new object();
        private byte[] m_recvData;
        private void clearRecvData()
        {
            clearRecvData(1024);
        }

        private void clearRecvData(int size)
        {
            lock (m_readLokcer)
            {
                if (size == 0)
                {
                    m_recvData = null;
                }
                if (m_recvData == null)
                {
                    m_recvData = new byte[size];
                }
                Array.Clear(m_recvData, 0, m_recvData.Length);
            }
        }


        public override bool IsOpen
        {
            get
            {
                return m_Client != null && m_Client.Connected;
            }
        }

        public override bool CanRead
        {
            get
            {
                bool rst = IsOpen;
                if (rst)
                { 
                    List<Socket> rList = new List<Socket>();
                    rList.Add(m_Client);
                    Socket.Select(rList, null, null, 1000);
                    if (rList != null && rList.Count == 1)
                    {
                        rst = true;
                    }
                }
                return rst;
            }
        }

        public override bool CanWrite
        {
            get
            {
                bool rst = IsOpen;
                if (rst)
                {
                    List<Socket> wList = new List<Socket>();
                    wList.Add(m_Client);
                    Socket.Select(null, wList, null, 1000);
                    if (wList != null && wList.Count == 1)
                    {
                        rst = true;
                    }
                }
                return rst;
            }
        }

        public override bool Open(string ip, int port)
        {
            m_Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                m_Client.Connect(ip, port);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("connect to : {0}:{1} error: {2}",ip,port,ex.Message);
            }
            return false;
        }



        public override bool Open(string name)
        {
            return Open(name, 5359);
        }

        public override int Write(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                Console.WriteLine("data is null");
                return ErrorCode.NoData;
            }
            byte[] bDatas = new byte[data.Length];
            Array.Clear(bDatas, 0, 1024);
            int idx = 0;
            foreach (char c in data)
            {
                bDatas[idx] = (byte)c;
            }
            if (CanWrite)
            {
                return m_Client.Send(bDatas);
            }
            return -1;
        }

        public string getReadString()
        {
            StringBuilder rB = new StringBuilder();

            lock (m_readLokcer)
            {
                if (m_recvData != null && m_recvData.Length > 0)
                {
                    foreach (byte rData in m_recvData)
                    {
                        rB.Append((char)rData);
                    }
                }
            }

            return rB.ToString();
        }

        public override string ReadString()
        {
            if (Read(1024) > 0)
            {
                return getReadString();
            }
            return string.Empty;
        }

        public byte[] getReadBytes()
        {
            lock (m_readLokcer)
            {
                return m_recvData;
            }
        }

        public byte[] ReadBytes()
        {
            if (Read(1024) > 0)
            {
                return getReadBytes();
            }
            return null;
        }

        public int Read(int size)
        {
            int nReads = 0;
            clearRecvData();
            if (CanRead)
            {
                try
                {
                    byte[] data = new byte[size];
                    nReads = m_Client.Receive(data);
                    if (nReads > 0)
                    {
                        lock (m_readLokcer)
                        {
                            clearRecvData(nReads);
                            Array.Copy(data, m_recvData, nReads);
                        }
                    }
                    return nReads;
                }
                catch (Exception ex)
                {
                    //ArgumentNullException 传递的 buffer 为 null。 
                    //InvalidOperationException 指定的端口未打开。
                    //ArgumentOutOfRangeException offset 或 count 参数超出了所传递的 buffer 的有效区域。 offset 或 count 小于零。 
                    //ArgumentException offset 加上 count 大于 buffer 的长度。 
                    //TimeoutException 没有可以读取的字节。
                    Console.WriteLine("Socket Write Error : {0}", ex.Message);
                    return ErrorCode.Exceptions;
                }
            }
            else
            {
                Console.WriteLine("Socket not open");
                return ErrorCode.NotOpen;
            }
            //return ErrorCode.UnkownError;
        }
    }
}
